package com.ibm.law.service;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

public abstract class DataAccessService<T> {
	private Class entityClass;
	static protected EntityManager entityManager = Persistence
			.createEntityManagerFactory("lawPU").createEntityManager();

	public void insert(T o) {
		entityManager.getTransaction().begin();
		entityManager.persist(o);
		entityManager.getTransaction().commit();
		// entityManager.clear();
	}

	public void update(T o) {
		entityManager.getTransaction().begin();
		entityManager.merge(o);
		entityManager.getTransaction().commit();
	}

	public void delete(T o) {
		entityManager.getTransaction().begin();
		entityManager.remove(o);
		entityManager.getTransaction().commit();
		// entityManager.clear();
	}

	public T get(Long id) {
		T o = (T) entityManager.find(entityClass, id);
		// entityManager.clear();
		return o;
	}

	public DataAccessService() {
		if (ParameterizedType.class.isAssignableFrom(getClass()
				.getGenericSuperclass().getClass())) {
			Type[] actualTypeArguments = ((ParameterizedType) getClass()
					.getGenericSuperclass()).getActualTypeArguments();
			entityClass = (Class<T>) actualTypeArguments[0];
		}

	}

	public List<T> getAll() {
		String jpql = "select o from " + entityClass.getSimpleName() + " o ";
		List<T> list = entityManager.createQuery(jpql, entityClass)
				.getResultList();
		// entityManager.clear();
		return list;
	}

	public void saveAll(List<T> os) {
		entityManager.getTransaction().begin();
		for (T o : os) {
			entityManager.persist(o);
		}
		entityManager.getTransaction().commit();
	}
}
